import { createStore } from 'redux';
import { getTodayDBName } from 'common/tool';

function reducer(state = {date: getTodayDBName(), list: []}, action) {
  console.log(action);
  let list;

  switch(action.type) {
    case 'SET_INIT_DATA':
      return {
        date: action.name,
        list: action.data,
      };
    
    case 'ADD_ITEM':
      list = state.list.slice();
      list.unshift(action.data);
      return Object.assign({}, state, {list});

    case 'UPDATE_ITEM':
      list = state.list.slice();
      list = list.map(item => item.id === action.data.id ? action.data : item);
      return Object.assign({}, state, {list});
    
    case 'DELETE_ITEM':
      list = state.list.slice();
      const index = list.findIndex(item => item.id = action.data)
      list.splice(index, 1);
      return Object.assign({}, state, {list});

    default:

      return state;
  }
}

export default createStore(reducer);
